package top.wintp.offlinedataanalysis.anlyser.mr.nu;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.wintp.offlinedataanalysis.anlyser.dao.DimensionBrowserDAO;
import top.wintp.offlinedataanalysis.anlyser.dao.DimensionDateDAO;
import top.wintp.offlinedataanalysis.anlyser.dao.DimensionKpiDAO;
import top.wintp.offlinedataanalysis.anlyser.dao.DimensionPlatformDAO;
import top.wintp.offlinedataanalysis.anlyser.dim.base.BrowserDimension;
import top.wintp.offlinedataanalysis.anlyser.dim.base.DateDimension;
import top.wintp.offlinedataanalysis.anlyser.dim.base.KpiDimension;
import top.wintp.offlinedataanalysis.anlyser.dim.base.PlatformDimension;
import top.wintp.offlinedataanalysis.anlyser.domain.DimensionBrowserExample;
import top.wintp.offlinedataanalysis.anlyser.domain.DimensionDateExample;
import top.wintp.offlinedataanalysis.anlyser.domain.DimensionKpiExample;
import top.wintp.offlinedataanalysis.anlyser.domain.DimensionPlatformExample;
import top.wintp.offlinedataanalysis.common.ConstantValues;
import top.wintp.offlinedataanalysis.util.StringUtils;

/**
 * @author: pyfysf
 * <p>
 * @qq: 337081267
 * <p>
 * @CSDN: http://blog.csdn.net/pyfysf
 * <p>
 * @blog: http://wintp.top
 * <p>
 * @email: pyfysf@163.com
 * <p>
 * @time: 2019/8/29
 */
public class MySqlCollector {
    private static final Logger logger = LoggerFactory.getLogger(MySqlCollector.class);

    private final Map<String, Integer> cacheIdMap = new HashMap<>();
    private final SqlSession session;

    public MySqlCollector(SqlSession session) {
        this.session = session;
    }

    public SqlSession getSession() {
        return session;
    }


    /**
     * 转换platform数据：
     * 如果存在获取id
     * 如果不存在插入之后获取id
     *
     * @param platform
     * @return
     */
    public Integer convertPlatformData(PlatformDimension platform) {
        String platformName = platform.getPlatformName();

        if (StringUtils.isEmpty(platformName) ) {
            return null;
        }

        String platformCacheKey = ConstantValues.PLATFORM_CACHE_KEY_PRE_TAG + platformName;

        Integer platformId = cacheIdMap.get(platformCacheKey);
        DimensionPlatformDAO dimensionPlatformDAO = session.getMapper(DimensionPlatformDAO.class);
        DimensionPlatformExample example = new DimensionPlatformExample();
        example.createCriteria().andPlatformNameEqualTo(platformName);
        List<PlatformDimension> dimensionPlatforms = dimensionPlatformDAO.selectByExample(example);
        if (dimensionPlatforms == null || dimensionPlatforms.size() == 0) {
            dimensionPlatformDAO.insert(platform);
            session.commit();
            platformId = platform.getId();
        } else {
            platformId = dimensionPlatforms.get(0).getId();
        }
        cacheIdMap.put(platformCacheKey, platformId);

        return platformId;
    }

    /**
     * 转换kpi数据：
     * 如果存在获取id
     * 如果不存在插入之后获取id
     *
     * @param kpi
     * @return
     */
    public Integer convertKpiData(KpiDimension kpi) {
        String kpiName = kpi.getKpiName();

        if (StringUtils.isEmpty(kpiName) ) {
            return null;
        }


        String kpiKey = ConstantValues.KPI_CACHE_KEY_PRE_TAG + kpi.getKpiName();
        Integer kpiId = cacheIdMap.get(kpiKey);

        if (kpiId != null) {
            return kpiId;
        }

        DimensionKpiDAO dimensionKpiDAO = session.getMapper(DimensionKpiDAO.class);

        DimensionKpiExample example = new DimensionKpiExample();
        example.createCriteria().andKpiNameEqualTo(kpiName);
        List<KpiDimension> dimensionKpis = dimensionKpiDAO.selectByExample(example);

        if (dimensionKpis == null || dimensionKpis.size() == 0) {
            //插入数据
            dimensionKpiDAO.insert(kpi);
            session.commit();
            kpiId = kpi.getId();
        } else {
            kpiId = dimensionKpis.get(0).getId();
        }
        cacheIdMap.put(kpiKey, kpiId);

        return kpiId;
    }

    /**
     * 转换日期数据：
     * 如果存在获取id
     * 如果不存在插入之后获取id
     *
     * @param date
     * @return
     */
    public Integer convertDateData(DateDimension date) {
        int year = date.getYear();
        int month = date.getMonth();
        int week = date.getWeek();
        int season = date.getSeason();
        int day = date.getDay();
        String type = date.getType();

        StringBuilder sb = new StringBuilder();
        sb.append(year)
                .append("_")
                .append(month)
                .append("_")
                .append(season)
                .append("_")
                .append(week)
                .append("_")
                .append(day)
                .append("_")
                .append(type)
        ;
        String dateCacheKey = sb.toString();

        //        获取缓存中是否存在
        Integer dateId = cacheIdMap.get(dateCacheKey);
        if (dateId != null) {
            return dateId;
        }

        // 缓存中不存在
        DimensionDateDAO dimensionDateDAO = session.getMapper(DimensionDateDAO.class);
        DimensionDateExample example = new DimensionDateExample();
        DimensionDateExample.Criteria criteria = example.createCriteria();
        criteria.andYearEqualTo(year)
                .andMonthEqualTo(month)
                .andSeasonEqualTo(season)
                .andWeekEqualTo(week)
                .andDayEqualTo(day)
                .andTypeEqualTo(type);
        List<DateDimension> dimensionDates = dimensionDateDAO.selectByExample(example);

        if (dimensionDates == null || dimensionDates.size() == 0) {
            //没有数据查询到
            dimensionDateDAO.insert(date);
            session.commit();

            dateId = date.getId();
        }
        if (dateId == null) {
            dateId = dimensionDates.get(0).getId();
        }

        // 写入缓存
        cacheIdMap.put(dateCacheKey, dateId);
        return dateId;
    }

    /**
     * 转换浏览器数据：
     * 如果存在获取id
     * 如果不存在插入之后获取id
     *
     * @param browser
     * @return
     */
    public Integer convertBrowserData(BrowserDimension browser) {
        String browserName = browser.getBrowserName();
        String browserVersion = browser.getBrowserVersion();

        if (StringUtils.isEmpty(browserName) || StringUtils.isEmpty(browserVersion)) {
            return null;
        }


        String browserKey = browserName + "_" + browserVersion;
        //        获取缓存中是否存在
        Integer browserId = cacheIdMap.get(browserKey);
        if (browserId != null) {
            return browserId;
        }

        //保存浏览器信息
        DimensionBrowserDAO dimensionBrowserDAO = session.getMapper(DimensionBrowserDAO.class);
        //查询是否存在
        DimensionBrowserExample browserInfoExample = new DimensionBrowserExample();
        DimensionBrowserExample.Criteria criteria = browserInfoExample.createCriteria();
        criteria.andBrowserNameEqualTo(browserName);
        criteria.andBrowserVersionEqualTo(browserVersion);
        List<BrowserDimension> dimensionBrowsers = dimensionBrowserDAO.selectByExample(browserInfoExample);
        //        不存在
        if (dimensionBrowsers == null || dimensionBrowsers.size() == 0) {
            dimensionBrowserDAO.insert(browser);
            session.commit();
        } else {
            browser = dimensionBrowsers.get(0);
        }

        browserId = browser.getId();

        // 添加到缓存中
        cacheIdMap.put(browserKey, browserId);

        return browserId;
    }

}
